<template>
  <!-- 新增/修改弹框 -->
  <el-dialog
    width="25%"
    :title="formData.id ? '编辑学科' : '新增学科'"
    :visible.sync="showDialog"
    @close="closeHandler"
  >
    <el-form
      v-if="showDialog"
      :model="formData"
      :rules="formRules"
      ref="form"
      label-width="100px"
    >
      <el-form-item prop="subjectName" label="学科名称">
        <el-input
          v-model="formData.subjectName"
          placeholder="请输入学科名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否显示" prop="isFrontDisplay">
        <el-switch
          v-model="formData.isFrontDisplay"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="">
        <el-button size="small" @click="showDialog = false">取消</el-button>
        <el-button size="small" type="primary" @click="addSubject"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import {
  addSubjectApi,
  editSubjectApi,
  getSubjectListApi,
} from "@/api/subjects";

export default {
  name: "addlist",
  data() {
    //新增学科查重
    const checkSublistRepeat = async (rule, value, cb) => {
      //先找到左右的学科名称
      let { items } = await getSubjectListApi({
        subjectName: "",
        page: 1,
        pagesize: 10000,
      });
      //找到兄弟们,判断是否和兄弟们同名
      let isRepeat = false;
      isRepeat = items.some((val) => {
        return val.subjectName === value;
      });
      isRepeat ? cb(new Error(`已经存在${value}这个学科名称`)) : cb();
    };
    return {
      //新增和修改弹框的表单数据
      formData: {
        subjectName: "",
        isFrontDisplay: "",
        id: "",
      },
      formRules: {
        subjectName: [
          { required: true, message: "请输入学科名称", trigger: "blur" },
          { validator: checkSublistRepeat, trigger: "blur" },
        ],
      },
      showDialog: false,
    };
  },
  methods: {
    //增加/修改学科提交数据
    async addSubject() {
      try {
        await this.$refs.form.validate();
      } catch (error) {
        return console.log(error);
      }
      if (this.formData.id) {
        await editSubjectApi(this.formData);
        this.$emit("updateList");
        this.$message.success("修改成功");
      } else {
        //发送请求
        await addSubjectApi(this.formData);
        this.$emit("updateList");
        this.$message.success("添加成功");
      }
      //关闭弹框
      this.showDialog = false;
      //清空输入框
      this.formData = {};
    },
    //关闭事件
    closeHandler() {
      //表单重置
      this.formData = {
        subjectName: "",
        isFrontDisplay: "",
        id: "",
      };
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  background-color: rgb(64, 158, 255);
}
::v-deep .el-dialog__title {
  color: #fff;
}
::v-deep .el-dialog__close {
  color: #fff;
}
</style>